/**
 * author: zhanggengtao<zhanggengt6670>
 * data: 2024-01-03
 * info：通过用户首选项实现数据持久化，Preferences存储数据不能超过1万条
 *       key：长度不能超过80字节
 *       value：长度不能超过8192字节
 */
import dataPreferences from "@ohos.data.preferences";
import { BusinessError } from '@ohos.base';
import preferences from '@ohos.data.preferences';
import { Context } from '@ohos.abilityAccessCtrl';

export class PreferencesData {
  static preferenceMap: Map<string, dataPreferences.Preferences>

  static getDataPreferences(name: string): dataPreferences.Preferences {
    if (this.preferenceMap.has(name)) {
      return this.preferenceMap.get(name)
    }
    return dataPreferences.getPreferencesSync(this.context, { name: name });
  }

  // 清除数据
  static async remove(name: string) {
    let preference: dataPreferences.Preferences = await dataPreferences.getPreferences(this.context, name);
    preference.clear();
  }

  // 数据写入-string
  static async putString(name: string, key: string, value: string) {
    let preference: dataPreferences.Preferences = this.getDataPreferences(name)
    await preference.put(key, value);
    await preference.flush();
  }

  // 数据写入-boolean
  static async putBoolean(context: Context, name: string, key: string, value: boolean) {
    let preference: dataPreferences.Preferences = await dataPreferences.getPreferences(this.context, name);
    await preference.put(key, value);
    await preference.flush();
  }

  // 数据写入-number
  static async putNumber(name: string, key: string, value: number) {
    let preference: dataPreferences.Preferences = await dataPreferences.getPreferences(this.context, name);
    await preference.put(key, value);
    await preference.flush();
  }

  // 数据取出-string
  static async getString(name: string, key: string): Promise<string> {
    let preference: dataPreferences.Preferences = await dataPreferences.getPreferences(this.context, name);
    return await preference.get(key, "") as string;
  }

  // // 数据取出-string
  // static getString2(name: string, key: string): preferences.ValueType {
  //   // let preference: dataPreferences.Preferences =  dataPreferences.getPreferences(this.getContext(), name);
  //   // return await preference.get(key, "") as string;
  //   return PreferencesData.preferences.getSync("1", 1);
  // }

  // 数据取出-boolean
  static async getBoolean(name: string, key: string): Promise<boolean> {
    let preference: dataPreferences.Preferences = await dataPreferences.getPreferences(this.context, name);
    return await preference.get(key, true) as boolean;
  }

  // 数据取出-number
  static async getNumber(name: string, key: string): Promise<number> {
    let preference: dataPreferences.Preferences = await dataPreferences.getPreferences(this.context, name);
    return await preference.get(key, 0) as number;
  }

  static context: Context

  static init(context) {
    this.context = context
  }
}